import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { AutomationTaskEntity } from '../../entity/task';

/**
 * 执行任务
 */
@Provide()
export class AutomationTaskService extends BaseService {
  @InjectEntityModel(AutomationTaskEntity)
  automationTaskEntity: Repository<AutomationTaskEntity>;

  /**
   * 根据流水线ID获取任务列表
   * @param pipelineId 
   */
  async getTasksByPipeline(pipelineId: number) {
    return await this.automationTaskEntity.find({
      where: { pipelineId },
      order: { order: 'ASC' }
    });
  }

  /**
   * 批量更新任务顺序
   * @param taskOrders 
   */
  async updateTaskOrders(taskOrders: { id: number; order: number }[]) {
    for (const taskOrder of taskOrders) {
      await this.automationTaskEntity.update(taskOrder.id, { order: taskOrder.order });
    }
    return '更新成功';
  }

  /**
   * 复制任务
   * @param id 
   */
  async copyTask(id: number) {
    const task = await this.automationTaskEntity.findOneBy({ id });
    if (!task) {
      throw new Error('任务不存在');
    }

    const newTask = { ...task };
    delete newTask.id;
    delete newTask.createTime;
    delete newTask.updateTime;
    newTask.description = `${newTask.description}_副本`;
    newTask.order = newTask.order + 1;

    return await this.automationTaskEntity.save(newTask);
  }

  /**
   * 获取设备的所有任务
   * @param deviceId 
   */
  async getTasksByDevice(deviceId: string) {
    return await this.automationTaskEntity.find({
      where: { deviceId },
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 获取任务执行统计
   */
  async getTaskStatistics() {
    const total = await this.automationTaskEntity.count();
    const openTasks = await this.automationTaskEntity.count({ where: { actionType: 0 } });
    const closeTasks = await this.automationTaskEntity.count({ where: { actionType: 1 } });
    const syncTasks = await this.automationTaskEntity.count({ where: { actionType: 2 } });

    return {
      total,
      openTasks,
      closeTasks,
      syncTasks,
      distribution: {
        open: total > 0 ? Math.round((openTasks / total) * 100) : 0,
        close: total > 0 ? Math.round((closeTasks / total) * 100) : 0,
        sync: total > 0 ? Math.round((syncTasks / total) * 100) : 0
      }
    };
  }
}